//
//  LKTestCell.m
//  YLHelper
//
//  Created by she1323 on 2018/5/8.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKTestCell.h"
#import "LKTestAnswerCell.h"
#import "LKTestChooseCell.h"
#import "LKTestAnswerAnalysicCell.h"


@interface LKTestCell()

@property(nonatomic,strong)NSIndexPath *selectIndex;


@end

@implementation LKTestCell

-(void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    NSLog(@"走你的方法");
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

-(void)setModel:(LKExaminationPaperQuestionModel *)model{
    _model = model;
    if (_model.hadSureAns) {
        self.sureAnswer = YES;
        if ([_model.questionBank.questionTypeTest isEqual:@"单选题"]) {
            for (NSInteger i = 0; i < self.model.questionBank.questionAnswer.count; i++) {
                if ([self.model.questionBank.questionAnswer[i].answerName isEqual:self.selectValue]) {
                    self.selectIndex = [NSIndexPath indexPathForRow:i inSection:0];
                }
            }
        }else{
            
        }

        
//        self.selectValue = self.kaoshiModel.questionBank.questionAnswer[self.selectIndex.row].answerName;
//        self.selectIndex = self.selectValue;
//        [self setUI];
    }else{
        self.selectIndex = nil;
        [self.selectArray removeAllObjects];
        [self setUI];
        self.sureAnswer = NO;
    }
    self.collectBtn.selected = _model.questionBank.isCollection;
    [self.tableView reloadData];
}
-(void)setKaoshiModel:(LKQuestionBankKaoshiModel *)kaoshiModel{
    _kaoshiModel = kaoshiModel;
    self.collectBtn.selected = _kaoshiModel.questionBank.isCollection;
    if (_kaoshiModel.hadSureKaoshiAnswer) {
        if ([_kaoshiModel.questionBank.questionTypeText isEqual:@"单选题"]) {
            for (NSInteger i = 0; i < _kaoshiModel.questionBank.questionAnswer.count; i++) {
                if ([_kaoshiModel.questionBank.questionAnswer[i].answerName isEqual:self.selectValue]) {
                    self.selectIndex = [NSIndexPath indexPathForRow:i inSection:0];
                }
            }
        }else{
            for (NSInteger i = 0; i < _kaoshiModel.questionBank.questionAnswer.count; i++) {
                for (NSInteger j = 0; j < self.selectArray.count; j++) {
                    if ([_kaoshiModel.questionBank.questionAnswer[i].answerName isEqual:self.selectArray[j]]) {
                        
                    }
                }
            }
        }

    }else{
          self.selectIndex = nil;
          [self.selectArray removeAllObjects];
    }
    [self setUI];
    [self.tableView reloadData];
}

-(void)setUI{
    
    [self.tableView registerNib:[UINib nibWithNibName:@"LKTestAnswerCell" bundle:nil] forCellReuseIdentifier:@"LKTestAnswerCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"LKTestChooseCell" bundle:nil] forCellReuseIdentifier:@"LKTestChooseCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"LKTestAnswerAnalysicCell" bundle:nil] forCellReuseIdentifier:@"LKTestAnswerAnalysicCell"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.estimatedSectionHeaderHeight = 200;
    self.tableView.estimatedRowHeight = 200;
    [self.tableView reloadData];
 
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.isKaoshi) {
        return 1;
    }
    if (!self.sureAnswer) {
        return 1;
    }
    return 3;

}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.isKaoshi) {
        return self.kaoshiModel.questionBank.questionAnswer.count;
    }
    if (section == 0) {
        LKQuestionBankModel *model = self.model.questionBank;
        return model.questionAnswer.count;
    }
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isKaoshi) {
        LKTestChooseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKTestChooseCell"];
        cell.model = self.kaoshiModel.questionBank.questionAnswer[indexPath.row];
        if ([self.kaoshiModel.questionBank.questionTypeText isEqual:@"单选题"]) {
            if (indexPath == self.selectIndex) {
                cell.chooseImageView.image = [UIImage imageNamed:@"elarningxuanzeright"];
            }else{
                cell.chooseImageView.image = [UIImage imageNamed:@"elarningweixuanze"];
            }
        }else{
            for (NSIndexPath *index in self.selectArray) {
                if (index == indexPath) {
                    cell.chooseImageView.image = [UIImage imageNamed:@"elarningxuanzeright"];
                    return cell;
                }
            }
            cell.chooseImageView.image = [UIImage imageNamed:@"elarningweixuanze"];
        }
        return cell;
    }
    LKTestChooseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKTestChooseCell"];
    if (indexPath.section == 1) {
        LKTestAnswerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKTestAnswerCell"];
        NSString *rightAns = @"正确答案：";
        for (LKQuestionAnswerModel *ansmodel in self.model.questionBank.questionAnswer) {
            if (ansmodel.isRight) {
                rightAns = [rightAns stringByAppendingString:ansmodel.answerName];
                [cell.righttn setTitle:rightAns forState:UIControlStateNormal];
            }
        }
        if ([self.model.questionBank.questionTypeTest isEqual:@"单选题"]) {
            NSString *selectAns = [NSString stringWithFormat:@"%@%@",@"您的答案：",self.selectValue];
            [cell.yourBtn setTitle:selectAns forState:UIControlStateNormal];
        }else{
            NSString *rightAns = @"您的答案：";
            for (NSInteger i = 0; i < self.selectArray.count; i++) {
                NSIndexPath *index = self.selectArray[i];
                rightAns = [rightAns stringByAppendingString:self.model.questionBank.questionAnswer[index.row].answerName];
                [cell.yourBtn setTitle:rightAns forState:UIControlStateNormal];
                
            }
            
        }

        return cell;
    }
    if (indexPath.section == 2) {
        LKTestAnswerAnalysicCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKTestAnswerAnalysicCell"];
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"答案解析：%@",self.model.questionBank.analysis]];
        
        [str addAttribute:NSForegroundColorAttributeName value:blueDefault range:NSMakeRange(0, 4)];
        [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, 4)];
        cell.contentLabel.attributedText = str;
        return cell;
    }
    cell.model = self.model.questionBank.questionAnswer[indexPath.row];
    if ([self.model.questionBank.questionTypeTest isEqual:@"单选题"]) {
        if (indexPath == self.selectIndex) {
            cell.chooseImageView.image = [UIImage imageNamed:@"elarningxuanzeright"];
        }else{
            cell.chooseImageView.image = [UIImage imageNamed:@"elarningweixuanze"];
        }
        return cell;
    }else{
        for (NSIndexPath *index in self.selectArray) {
            if (index == indexPath) {
                cell.chooseImageView.image = [UIImage imageNamed:@"elarningxuanzeright"];
//                cell.chooseImageView.image = [UIImage imageNamed:@"elarningweixuanze"];
                return cell;
            }
        }
        cell.chooseImageView.image = [UIImage imageNamed:@"elarningweixuanze"];
    }
    return cell;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (self.isKaoshi) {
        UIView *headerView = [[UIView alloc] init];
        headerView.backgroundColor = [UIColor whiteColor];
        if (section == 0) {
            NSString *questionTitle = [NSString stringWithFormat:@"【%@】%@",self.kaoshiModel.questionBank.questionTypeText,self.kaoshiModel.questionBank.questionCountent];
            LKBaseLabel *label = [LKBaseLabel labelWithFrame:CGRectZero text:questionTitle textColor:COLOR_HEX(0x929292) font:[UIFont systemFontOfSize:15] textAlignment:NSTextAlignmentLeft backgroundColor:[UIColor whiteColor]];
            label.numberOfLines = 0;
            [headerView addSubview:label];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(headerView.mas_left).offset(16);
                make.right.equalTo(headerView.mas_right).offset(-16);
                make.top.equalTo(headerView.mas_top).offset(21);
                make.bottom.equalTo(headerView.mas_bottom).offset(-21);
            }];
        }
        return headerView;
    }
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor whiteColor];
    if (section == 0) {
        NSString *questionTitle = [NSString stringWithFormat:@"【%@】%@",self.model.questionBank.questionTypeTest,self.model.questionBank.questionCountent];
        LKBaseLabel *label = [LKBaseLabel labelWithFrame:CGRectZero text:questionTitle textColor:COLOR_HEX(0x929292) font:[UIFont systemFontOfSize:15] textAlignment:NSTextAlignmentLeft backgroundColor:[UIColor whiteColor]];
        label.numberOfLines = 0;
        [headerView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(headerView.mas_left).offset(16);
            make.right.equalTo(headerView.mas_right).offset(-16);
            make.top.equalTo(headerView.mas_top).offset(21);
            make.bottom.equalTo(headerView.mas_bottom).offset(-21);
        }];
        if (self.sureAnswer) {
            UIImageView *imagIconV = [[UIImageView alloc] init];
            if ([self.model.questionBank.questionTypeTest isEqual:@"单选题"]) {
                NSString *rightAns = @"";
                for (LKQuestionAnswerModel *ansmodel in self.model.questionBank.questionAnswer) {
                    if (ansmodel.isRight) {
                        rightAns = [rightAns stringByAppendingString:ansmodel.answerName];
                    }
                }
                if ([rightAns isEqual:self.selectValue]) {
                    if (self.hithithit) {
                        self.hithithit = NO;
                        self.rightNumbersCount += 1;
                    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@" %ld",self.rightNumbersCount] forKey:@"testRightAccount"];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        [self.rightNumberBtn setTitle:[NSString stringWithFormat:@" %ld",self.rightNumbersCount] forState:UIControlStateNormal];
                    }
                    imagIconV.image = [UIImage imageNamed:@"youransweright"];
                }else{
                    if (self.hithithit) {
                        self.hithithit = NO;
                        self.wrongNumbersCount += 1;
                        [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@" %ld",self.wrongNumbersCount] forKey:@"testWrongAccount"];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        [self.correctBtn setTitle:[NSString stringWithFormat:@" %ld",self.wrongNumbersCount] forState:UIControlStateNormal];
                    }
                    imagIconV.image = [UIImage imageNamed:@"youranswewrong"];
                }
            }else{
                NSMutableArray *answerArray = [[NSMutableArray alloc] init];
                for (LKQuestionAnswerModel *ansmodel in self.model.questionBank.questionAnswer) {
                    if (ansmodel.isRight) {
                        [answerArray addObject:ansmodel.answerName];
                    }
                }
                if ([self array:answerArray isEqualTo:self.selectArray]) {
                    if (self.hithithit) {
                        self.hithithit = NO;
                        self.rightNumbersCount += 1;
                        [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@" %ld",self.rightNumbersCount] forKey:@"testRightAccount"];
                        [[NSUserDefaults standardUserDefaults] synchronize];                [self.rightNumberBtn setTitle:[NSString stringWithFormat:@" %ld",self.rightNumbersCount] forState:UIControlStateNormal];
                    }
                    imagIconV.image = [UIImage imageNamed:@"youransweright"];
                }else{
                    if (self.hithithit) {
                        self.hithithit = NO;
                        self.wrongNumbersCount += 1;
                        [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@" %ld",self.wrongNumbersCount] forKey:@"testWrongAccount"];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        [self.correctBtn setTitle:[NSString stringWithFormat:@" %ld",self.wrongNumbersCount] forState:UIControlStateNormal];
                    }

                    imagIconV.image = [UIImage imageNamed:@"youranswewrong"];
                }
            }
            [headerView addSubview:imagIconV];
            [label mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(headerView.mas_left).offset(36);
                make.right.equalTo(headerView.mas_right).offset(-16);
                make.top.equalTo(headerView.mas_top).offset(21);
                make.bottom.equalTo(headerView.mas_bottom).offset(-21);
            }];
            [imagIconV mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(label.mas_left).offset(-2);
                make.centerY.equalTo(label.mas_centerY);
            }];
        }
        
    }
    
    return headerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==1) {
        return 120;
    }
    if (indexPath.section == 2) {
        return UITableViewAutomaticDimension;
    }
    return UITableViewAutomaticDimension;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    [self setBottomRightsAndWrongNumber];
    return section == 0 ? UITableViewAutomaticDimension:0.0000000001;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc] init];
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isKaoshi) {
        if ([self.kaoshiModel.questionBank.questionTypeText isEqual:@"单选题"]) {
            if (self.selectIndex == indexPath) {
                self.selectIndex = nil;
                self.selectValue = nil;
                
            }else{
                self.selectIndex = indexPath;
                self.selectValue = self.kaoshiModel.questionBank.questionAnswer[self.selectIndex.row].answerName;
            }
        }else{
            if (self.selectArray.count != 0) {
                for (NSInteger i = 0; i < self.selectArray.count; i++) {
                    NSIndexPath *index = self.selectArray[i];
                    if (index == indexPath) {
                        [self.selectArray removeObject:index];
                        [tableView reloadSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
                        return;
                    }
                }
                [self.selectArray addObject:indexPath];
            }else{
                [self.selectArray addObject:indexPath];
            }
            NSString *rightAns = @"";
            for (NSInteger i = 0; i < self.selectArray.count; i++) {
                NSIndexPath *index = self.selectArray[i];
                rightAns = [rightAns stringByAppendingString:self.kaoshiModel.questionBank.questionAnswer[index.row].answerName];
            }
            self.selectValue = rightAns;
            NSLog(@"多选题选项%@", self.selectValue);
        }
        [tableView reloadSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
        return;
    }
    if (self.sureAnswer) {
        return;
    }
    if (indexPath.section == 0) {
        if ([self.model.questionBank.questionTypeTest isEqual:@"单选题"]) {
            if (self.selectIndex == indexPath) {
                self.selectIndex = nil;
                self.selectValue = nil;

            }else{
                self.selectIndex = indexPath;
                self.selectValue = self.model.questionBank.questionAnswer[self.selectIndex.row].answerName;
                
            }
        }else{
            if (self.selectArray.count != 0) {
                for (NSInteger i = 0; i < self.selectArray.count; i++) {
                    NSIndexPath *index = self.selectArray[i];
                    if (index == indexPath) {
                        [self.selectArray removeObject:index];
                        [tableView reloadSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
                        return;
                    }
                }
                [self.selectArray addObject:indexPath];
            }else{
                 [self.selectArray addObject:indexPath];
            }
            NSString *rightAns = @"";
            for (NSInteger i = 0; i < self.selectArray.count; i++) {
                NSIndexPath *index = self.selectArray[i];
                rightAns = [rightAns stringByAppendingString:self.model.questionBank.questionAnswer[index.row].answerName];
            }
            self.selectValue = rightAns;
            NSLog(@"多选题选项%@", self.selectValue);
        }

        [tableView reloadSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
    }

}
- (IBAction)collectAction:(id)sender {

    UIButton *btn = (UIButton *)sender;
    if (!btn.selected) {
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:examTestCollectUrl header:[LKUserInforTool header] parameters:@{@"Id":self.model.questionBankId} progress:^(NSProgress * _Nullable progress) {
            
        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
            [SVProgressHUD showInfoWithStatus:@"习题收藏成功"];
        } failure:^(NSString * _Nullable errorMessage) {
            
        }];
    }else{
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:examTestCancelCollectUrl header:[LKUserInforTool header] parameters:@{@"Id":self.model.questionBankId} progress:^(NSProgress * _Nullable progress) {
            
        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
            [SVProgressHUD showInfoWithStatus:@"习题取消收藏"];
        } failure:^(NSString * _Nullable errorMessage) {
            
        }];
    }
    btn.selected = !btn.selected;

}


-(NSMutableArray *)selectArray{
    if (!_selectArray) {
        _selectArray = [[NSMutableArray alloc] init];
    }
    return _selectArray;
}


/**
 比较两个数组中的元素是否相同

 @param array1 多选的答案
 @param array2 默认答案
 @return 是否相同
 */
- (BOOL)array:(NSArray *)array1 isEqualTo:(NSArray *)array2 {
    if (array1.count != array2.count) {
        return NO;
    }
    for (NSString *str in array1) {
        if (![array2 containsObject:str]) {
            return NO;
        }
    }
    return YES;
    
}

/**
 设置底部按钮的正确和错误的显示数量
 */
-(void)setBottomRightsAndWrongNumber{
    self.wrongNumbersCount = [[[[[NSUserDefaults standardUserDefaults] objectForKey:@"testWrongAccount"] componentsSeparatedByString:@" "] lastObject] integerValue];
    self.rightNumbersCount = [[[[[NSUserDefaults standardUserDefaults] objectForKey:@"testRightAccount"] componentsSeparatedByString:@" "] lastObject] integerValue];
    NSLog(@"正确个数%ld",self.rightNumbersCount);
    NSLog(@"错误个数%ld",self.wrongNumbersCount);
    NSString *rightsNumber = [NSString stringWithFormat:@" %ld",self.rightNumbersCount];
    NSString *wrongNumber = [NSString stringWithFormat:@" %ld",self.wrongNumbersCount];
    [self.correctBtn setTitle:wrongNumber forState:UIControlStateNormal];
    [self.rightNumberBtn setTitle:rightsNumber forState:UIControlStateNormal];

}

@end
